package cn.yy.cloudpay.usb;

import android.content.Context;

import com.android.usbport.ModbusTransfer;

import org.apache.log4j.Logger;

import cn.yy.cloudpay.scan.FeixiScanTActivity;
import cn.yy.cloudpay.util.SerialUtils;
import cn.yy.cloudpay.util.StringUtil;
import cn.yy.cloudpay.view.ToastUtil;

/**
 * Created by Administrator on 2018/1/27.
 */

public class ComTUtil {
    public Logger log= Logger.getLogger(this.getClass());
    private Context mContext;
    private FeixiScanTActivity activity;
    private int l=6;
    private int x = 3;
    private String redaddr = "026E";
    public static int write_1 = 414; //开机
    public static int write_2 = 416;//停机
    private boolean isCheck = true;
    private boolean is_send_statrt = false;

    public static ComTUtil instance(Context context){
        ComTUtil comm = new ComTUtil(context);
        comm.l = 20;
        comm.x = 20;
        return comm;
    }

    private ComTUtil(Context context){
        this.mContext = context;
        this.activity = (FeixiScanTActivity)mContext;
    }

    //检测是否可以支付
    public void checkPay(){
        log.info("===开始是否可以支付");
        try {
            activity.startin = 180;//等待进车，3分钟
            activity.stopix = 20;   //停机 20 秒内
//            activity.startix = 20;
            final byte[] ret = ModbusTransfer.getInstance(mContext).readDataFromPlc(
                    Integer.parseInt("1"),
                    StringUtil.hexStr2Bytes(redaddr.trim()),
                    Integer.parseInt("1"),
                    3000);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (ret != null) {
                        try {
                            log.info("checkPay 读取成功");
                            String rs = StringUtil.byte2HexStr(ret);
                            log.info("获取字节：" + rs);
                            int equiment = Integer.valueOf(rs);
                            if (equiment == 7||equiment == 8) {
                                log.info(rs + ":待机中 打开扫描支付");
                                activity.setEquiment(equiment);
                                activity.sendPay();
                            } else {
                                log.info(rs + ":设备正在使用中，请稍候再支付");
                                activity.getStatesStr().setText("设备状态:"+equiment+" 非停机状态");
                                activity.startScannerHandler("设备状态:"+equiment+" 非停机状态");
                            }
                        } catch (Exception ex) {
                            log.error("checkPay 异常" + ex);
                            restartCheckPay();
                        }
                    } else {
                        restartCheckPay();
                    }
                }
            });
        }catch (Exception ex){
            log.error("checkPay-send 异常"+ex);
            restartCheckPay();
        }
    }

    private void restartCheckPay(){
        l--;
        if(l>=0){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info(redaddr+":检测是否可以支付 "+l);
            activity.getStatesStr().setText(redaddr+":检测是否可以支付 "+l);
            checkPay();
        }else{
            log.info(redaddr+":检测完成");
            ToastUtil.showToast(mContext, "检测是否可以支付，读取数据失败", ToastUtil.FAIL);
            activity.startScannerHandler("检测是否可以支付，读取数据失败");
        }
    }

    //发送启动设备指令
    public void startup(final int key){
        log.info("===开始发送指令");
        try {
            String adr = SerialUtils.readAddr(key);
            String data = SerialUtils.readData(1);
            final byte[] ret = ModbusTransfer.getInstance(mContext).sendCmdToPlc(
                    Integer.parseInt("1"),
                    StringUtil.hexStr2Bytes(adr),
                    StringUtil.hexStr2Bytes(data));
            final String result = ret==null? "指令发送失败！" : "指令发送成功："+ StringUtil.byte2HexStr(ret);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    isCheck = false;
                    activity.stopCheck();
                    if(ret==null&&l>=0){
                        restartup(key);
                    }else if(ret!=null){
                        log.info(result+","+key);
                        activity.getStatesStr().setText("指令发送成功:"+key);
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        isCheck = true;
                        activity.checkState();
                    }else{
                        log.info(key+":指令发送失败");
                        activity.getStatesStr().setText("指令发送失败");
                        activity.startScannerHandler("指令发送失败");
                    }
                }
            });
        }catch(Exception ex){
            log.error("startup-send 异常"+ex);
            restartup(key);
        }
    }

    public void restartup(int key){
        l--;
        log.info(key+":指令发送失败 继续发送"+l);
        activity.getStatesStr().setText("指令发送失败 继续发送"+l);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        startup(key);
    }

    //实时检测状态
    public void checkState(){
        try {
            if(!isCheck){
                return;
            }
            final byte[] ret = ModbusTransfer.getInstance(mContext).readDataFromPlc(
                    Integer.parseInt("1"),
                    StringUtil.hexStr2Bytes(redaddr.trim()),
                    Integer.parseInt("1"),
                    3000);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(ret != null) {
                        try{
                            log.info("checkState 读取成功");
                            String rs = StringUtil.byte2HexStr(ret);
                            log.info("获取字节："+rs);
                            int equiment = Integer.valueOf(rs,10);

                            //上次警告，已停机，等待处理
                             if(activity.getEquiment()==9
                                      &&equiment==7){
                                log.info("等待远程指令");
                                activity.getStatesStr().setText("等待远程指令");
                                 //收远程数据 5 分钟
                                 activity.startix--;
                                 if(activity.startix<1){
                                     log.info("未进车，洗车完成，结束");
                                     activity.stopCheck();
                                     activity.startScannerHandler("未进车，洗车完成，结束");
                                     activity.setEquiment(equiment);
                                 }
                                return;
                             } else if(activity.getEquiment()==7&&equiment==7){
                                 log.info(rs + ":等待进车。");
                                 activity.getStatesStr().setText("等待进车 状态："+equiment);
                                 activity.startin--;
                                 if(activity.startin<1){
                                     log.info("未进车，洗车完成，结束");
                                     activity.stopCheck();
                                     activity.startScannerHandler("未进车，洗车完成，结束");
                                     activity.setEquiment(equiment);
                                 }
                                //等待3分钟
                                 return;
                             }else if((equiment==1||equiment==7)){
                                log.info("洗车完成，结束");
                                activity.stopCheck();
                                activity.startScannerHandler("洗车完成，结束 状态："+equiment);
                                activity.setEquiment(equiment);
                            }
                            //警告时停机
                            else if(equiment==9){
                                activity.sendMsg();
                                log.info("警告，停机:"+activity.stopix);
                                activity.getStatesStr().setText("警告，停机:"+activity.stopix);
                                activity.stopix--;
                                  try {
                                      Thread.sleep(1000);
                                  } catch (InterruptedException e) {
                                      e.printStackTrace();
                                  }
                                if(activity.stopix>0){
                                    startup(ComTUtil.write_2);
                                }else{
                                    log.info("警告，停机失败");
                                    activity.stopCheck();
                                    activity.startScannerHandler("警告，停机失败");
                                }
                                activity.setEquiment(equiment);
                                return;
                            }
//                            //上次非运行或警告，需重新开机
//                           else  if(equiment==success&&redaddr.equals("0004")){
//                                log.info("开机:"+activity.startix);
//                                activity.getStatesStr().setText("开机:"+activity.startix);
//                                activity.startix--;
//                                  try {
//                                      Thread.sleep(1000);
//                                  } catch (InterruptedException e) {
//                                      e.printStackTrace();
//                                  }
//                                if(activity.startix>0){
//                                    startup(ComUtil.write_1);
//                                }else{
//                                    log.info("开机失败");
//                                    activity.stopCheck();
//                                    activity.startScannerHandler("开机失败");
//                                }
//                                activity.setEquiment(equiment);
//                                return;
//                            }
                           else if(equiment!=7){
                                log.info(rs + ":启动成功，正在运行 状态："+equiment);
                                activity.getStatesStr().setText("启动成功，正在运行 状态："+equiment);
                                activity.setEquiment(equiment);
                            }
                            activity.ix = 20;
                            activity.stopix = 20;
//                            activity.startix = 20;
                        }catch (Exception ex){
                            log.error("checkState 异常"+ex);
                            activity.stopCheck();
                            activity.startScannerHandler("状态检测异常");
                        }
                    }else{
                        recheckState();
                    }
                }
            });
        }catch (Exception ex){
            log.error("checkState-send 异常"+ex);
            recheckState();
        }
    }

    public void recheckState(){
        activity.ix--;
        if(activity.ix<1){
            activity.stopCheck();
            activity.startScannerHandler("检测状态,读取数据失败");
            return;
        }
        log.info(redaddr+":检测状态,读取数据失败");
        activity.getStatesStr().setText("检测状态,读取数据失败:"+activity.ix);
    }
}
